package com.hllxd.hism.star.basic.service.model.dapan;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.*;

/**
 * 大盘数据包
 * @author xiyong.lxy
 * @date 2018-9-15 16:33
 */
@Data
@Slf4j
public class DapanPkg {
    /** 质量分 */
    private Double score;

    /** 异常汇总 */
    private List<DapanExpEntity> expList;

    /** Top10 */
    private TopNResult topNResult;




    /** 大盘方框显示的最新值和比较值 */
    private List<DapanCountEntity> dapanCountResult;

    /** 业务指标 */
    private List<DapanYeWuEntity> yeWuResult;

    public static DapanPkg buildPkg(List<DapanExpEntity> expList, List<DapanYeWuEntity> dapanYeWuEntityList, List<DapanCountEntity> dapanCountResult, TopNResult topNResult) {
        DapanPkg thiz = new DapanPkg();
        thiz.setExpList(expList);
        thiz.setYeWuResult(dapanYeWuEntityList);
        thiz.setDapanCountResult(dapanCountResult);
        thiz.setTopNResult(topNResult);
        return thiz;
    }

    public static List<DapanExpEntity> buildExpList(List<BillReportEntity> billReportEntityList, String pageName) {
        if (billReportEntityList != null) {
            log.info("billReportEntityList:{}", billReportEntityList.size());
            List<DapanExpEntity> list = new ArrayList<>();
            Map<String, DapanExpEntity> map = new TreeMap<>();
            for (BillReportEntity entity : billReportEntityList) {
                String id = entity.getId();
                String content = entity.getContent();
                BigDecimal[] items = Utils.str2Arr(content);

                String date = entity.getReportdate();
                List<Object> point = null;
                if (items != null) {
                    point = new ArrayList<Object>() {{
                        add(date);
                        add(getItem(pageName, items));
                    }};
                } else {
                    point = new ArrayList<Object>() {{
                        add(date);
                        add(0);
                    }};
                }
                if (map.containsKey(id)) {
                    //map中存在则添加值到list
                    map.get(id).getCntList().add(point);
                    if (items != null) {
                        map.get(id).setCnt(getItem(pageName, items));
                    } else {
                        map.get(id).setCnt(BigDecimal.ZERO);
                    }
                } else {//不存在则新建
                    List<List<Object>> cntList = new ArrayList<>();
                    cntList.add(point);
                    DapanExpEntity dapanExpEntity = DapanExpEntity.build(id, getItem(pageName, items), cntList);
                    map.put(id, dapanExpEntity);
                }
            }
            list.addAll(map.values());
            log.info("list {}", list.size());
            return list;
        } else {
            log.warn("billReportEntityList is null.");
            return null;
        }
    }

    public static List<DapanYeWuEntity> buildYewuList(List<QuotaEntity> quotaEntityList) {

        List<DapanYeWuEntity> yeWuList = new ArrayList<>();
        //TreeMap保证数据和list的顺序一致
        Map<String, DapanYeWuEntity> map = new TreeMap<>();
        for (QuotaEntity entity : quotaEntityList) {
            String id = entity.metaID;
            BigDecimal val = Utils.toBigDecimal(entity.getContent());
            String date = entity.reportDate.substring(0,10);
            if (map.containsKey(id)) {
                DapanYeWuEntity entityInMap = map.get(id);
                entityInMap.getDateList().add(date);
                entityInMap.getCountList().add(val);
            } else {
                List<Object> dateList = new ArrayList<Object>() {{
                    add(date);
                }};
                List<BigDecimal> countList = new ArrayList<BigDecimal>() {{
                    add(val);
                }};//count数组
                DapanYeWuEntity dapanYeWuEntity = DapanYeWuEntity.build(id, dateList, countList, null, null);
                map.put(id, dapanYeWuEntity);
            }
        }
        yeWuList.addAll(map.values());
        log.info("yeWuList {}", yeWuList.size());
        return yeWuList;
    }
    public static DapanCountEntity transToCompare(String series) {
        if(series==null) {
            return null;
        }
        log.info("{}",series);
        List<BigDecimal> countList = new ArrayList<>();
        String[] items = series.split(",");
        for(String item: items) {
            String[] kv = item.split("\\^");
            BigDecimal v = BigDecimal.ZERO;
            if(kv.length==2) {
                v = Utils.toBigDecimal(kv[1]);
            }
            countList.add(v);
        }
        return compareData(null, countList);
    }
    public static DapanCountEntity compareData(String id, List<BigDecimal> countList) {
        int sizeCount = countList.size();
        if(sizeCount==0) {
            return null;
        }
        BigDecimal sumCount = BigDecimal.ZERO;
        BigDecimal currValCount = countList.get(sizeCount - 1);

        // 获取30天数据的均值
        for (BigDecimal item : countList) {
            sumCount = BigdecimalArithUtil.bigAdd(sumCount, item);
        }
        BigDecimal avgValCount = BigdecimalArithUtil.bigDiv(sumCount, BigDecimal.valueOf(sizeCount));
        BigDecimal comAvgCount = BigdecimalArithUtil.bigDiv(BigdecimalArithUtil.bigSub(currValCount, avgValCount), avgValCount);

        //前一日的值
        BigDecimal comPreCount = BigDecimal.ZERO;
        if (sizeCount - 2 > -1) {
            BigDecimal preValCount = countList.get(sizeCount - 2);
            comPreCount = BigdecimalArithUtil.bigDiv(BigdecimalArithUtil.bigSub(currValCount, preValCount), preValCount);
        }
        return DapanCountEntity.build(id,
                com.hllxd.hism.star.basic.service.model.dapan.Formatter.scale(comPreCount.doubleValue() * 100, 2),
                com.hllxd.hism.star.basic.service.model.dapan.Formatter.scale(comAvgCount.doubleValue() * 100, 2),
                currValCount,
                sizeCount);
    }

    public static List<DapanCountEntity> transToCompare(List<DapanYeWuEntity> dapanYeWuEntityList) {
        // 添加业务最新值，均值，比较值等数据
        List<DapanCountEntity> dapanCountEntityList = new ArrayList<>();
        for (DapanYeWuEntity entity : dapanYeWuEntityList) {
            dapanCountEntityList.add(
                    compareData(entity.id, entity.getCountList()));
        }
        log.info("{}", JSON.toJSONString(dapanCountEntityList));
        return dapanCountEntityList;
    }

    public static TopNResult buildTop10(TopNResult topNResult) {
        // 遍历topNList添加值到
        Map<String, TopNEntity> map = new HashMap<>();
        for (TopNEntity entity : topNResult.getTopNEntityList()) {
            String id = entity.getShop_id();
            if (map.containsKey(id)) {
                map.get(id).setContent(Utils.sumContent(entity.getContent(), map.get(id).getContent()));
            } else {
                map.put(id, entity);
            }
        }
        List<TopNEntity> topNEntityList = new ArrayList<>(map.values());
        Collections.sort(topNEntityList);
        TopNResult result;
        if (topNEntityList.size() > 9) {
            result = TopNResult.build(topNEntityList.subList(0, 10));
        } else {
            result = TopNResult.build(topNEntityList.subList(0, topNEntityList.size()));
        }
        log.info("buildTop10 result:{}", result.getTopNEntityList().size());
        return result;
    }


    private static BigDecimal getItem(String pageName, BigDecimal[] items) {
        //不同类型返回不同值
        if ("shop".equals(pageName) && items.length > 1) {
            return items[1];
        } else {
            return items[0];
        }
    }
}
